##################################################################
# File : /lua/system/baseclass.lua
# Description : Base class definitions
# Author : Neruz
##################################################################

#
# Support for LUA-only objects.
#
local oldIsDestroyed = IsDestroyed
function _G.IsDestroyed(obj)
	return obj.__IsDestroyed or oldIsDestroyed(obj)
end

--[[
This is a base class for LUA-only classes to support Destroy().
OnCreate and OnDestroy should be overloaded.
Includes ForkThread.
--]]
LuaBaseClass = Class {
	__init = function(self, spec)
		self._trash = TrashBag()
		self:OnCreate(spec)
	end, 

	ForkThread = function(self, fn, ...)
		if fn then
			local thread = ForkThread(fn, self, unpack(arg))
			self._trash:Add(thread)
			return thread
		else
			return nil
		end
	end, 

	#
	# Override the object's metatable, when index is accessed, it'll return nil and LOG a WARN.
	#
	Destroy = function(self)
		self:OnDestroy()
		local destroyedFrom = debug.traceback('Object has been destroyed from:')
		local oldMeta = getmetatable(self)
		metatable = {	
			__index = function(self, key)
				local _type = type(rawget(oldMeta, key))
				WARN('Tried to access key: [', key, ' = ', _type,  '] but object is destroyed\n', destroyedFrom)
				return nil
			end, 
		}
		setmetatable(self, metatable)
		self.__IsDestroyed = true
		self._trash:Destroy()
	end, 

	OnCreate = function(self, spec)
	end, 

	OnDestroy = function(self)
	end, 
}